/*
 * Copyright (C) 2022 xuexiangjys(xuexiangjys@163.com)
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */

package com.ynkj.teleprompter.utiles;

import android.app.Activity;
import android.content.Context;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.Window;

import java.lang.reflect.Field;
import java.lang.reflect.Method;

public class SystemBarHelper {
    private static final String TAG = "SystemBarHelper";
    private int mStatusBarHeight = 0;
    private int mNavigationBarHeight = 0;

    public SystemBarHelper(Context context) {
        mStatusBarHeight = getStatusBarHeight(context);
        mNavigationBarHeight = getNavigationBarHeight(context);
    }

    public int getStatusBarHeight() {
        return mStatusBarHeight;
    }

    public int getNavigationBarHeight() {
        return mNavigationBarHeight;
    }

    public void modifyStatusBar(Activity activity, int color) {
        modifyStatusBar(activity.getWindow(), color);
    }

    public void modifyStatusBar(Window window, int color) {
        if (Utilities.isAtLeastL()) {
            modifyLolipop(window, color);
        } else if (Utilities.isAtLeastKK()) {
            modifyKitkat(window);
        }
    }

    public void modifyNavigationBar(Activity activity, int color) {
        modifyNavigationBar(activity.getWindow(), color);
    }

    public boolean isHideNavigationBar(Window window) {
        return (window.getAttributes().systemUiVisibility & View.SYSTEM_UI_FLAG_HIDE_NAVIGATION)
                == View.SYSTEM_UI_FLAG_HIDE_NAVIGATION;
    }

    public void modifyNavigationBar(Window window, int color) {
        if (!Utilities.isAtLeastL()) {
            return;
        }

        try {
            Class<?> clazz = window.getClass();
            
            int drawSysBarFlags = getWindowManagerLayoutParamsFlag("FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS");
            if (drawSysBarFlags > 0) {
                window.addFlags(drawSysBarFlags);
            }
            
            Method methodClearFlags = clazz.getMethod("clearFlags", Integer.TYPE);
            int flagTranslucent = getWindowManagerLayoutParamsFlag("FLAG_TRANSLUCENT_NAVIGATION");
            if (flagTranslucent > 0) {
                methodClearFlags.invoke(window, flagTranslucent);
            }
            window.getAttributes().systemUiVisibility |= View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION;
            
            Method naviBarColor = clazz.getMethod("setNavigationBarColor", Integer.TYPE);
            naviBarColor.invoke(window, color);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void setNavigationButtonWhite(Activity activity, boolean isLightStatsBar) {
        setNavigationButtonWhite(activity.getWindow(),isLightStatsBar);
    }
    //zhangqr  add for bug 320766 start
    public void setNavigationButtonWhite(Window window, boolean isLigthStatsBar) {
        int uiOptions = window.getDecorView().getSystemUiVisibility();

        if (isLigthStatsBar)
            uiOptions |= View.SYSTEM_UI_FLAG_LIGHT_NAVIGATION_BAR;
        else
            uiOptions |= 0x00000020;
        //zhangqr  add for bug 320766  end
        window.getDecorView().setSystemUiVisibility(uiOptions);
    }

    public void modifyKitkat(Window window) {
        int statusFlag = getWindowManagerLayoutParamsFlag("FLAG_TRANSLUCENT_STATUS");
        if (statusFlag > 0) {
            window.addFlags(statusFlag);
        }
    }

    public void modifyLolipop(Window window, int color) {
        window.getAttributes().systemUiVisibility |= (View.SYSTEM_UI_FLAG_LAYOUT_STABLE | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
        try {
            int flags = getWindowManagerLayoutParamsFlag("FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS");
            window.addFlags(flags);

            Class<?> clazz = window.getClass();

            Method methodClearFlags = clazz.getMethod("clearFlags",
                    Integer.TYPE);
            int flagTranslucentStatus = getWindowManagerLayoutParamsFlag("FLAG_TRANSLUCENT_STATUS");
            methodClearFlags.invoke(window, flagTranslucentStatus);

            Method methodStatusBar = clazz.getMethod("setStatusBarColor",
                    Integer.TYPE);
            methodStatusBar.invoke(window, color);
        } catch (Exception e) {
            Log.d(TAG, "setSystemBarStyle e = " + e.toString());
        }
    }

    public static int getStatusBarHeight(Context context) {
        if (!Utilities.isAtLeastIceCream()) {
            return 0;
        }

        int statusHeight = 0;
        Class<?> localClass;
        try {
            localClass = Class.forName("com.android.internal.R$dimen");
            Object object = localClass.newInstance();
            int height = Integer.parseInt(localClass
                    .getField("status_bar_height").get(object).toString());
            statusHeight = context.getResources().getDimensionPixelSize(height);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return statusHeight;
    }

    public static int getNavigationBarHeight(Context context) {
        if (!Utilities.isAtLeastL() || !hasNavigationBar(context)) {
            return 0;
        }

        int navigationBarHeight = 0;
        Class<?> localClass;
        try {
            localClass = Class.forName("com.android.internal.R$dimen");
            Object object = localClass.newInstance();
            int height = Integer.parseInt(localClass
                    .getField("navigation_bar_height").get(object).toString());
            navigationBarHeight = context.getResources().getDimensionPixelSize(height);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return navigationBarHeight;
    }

    public static boolean hasNavigationBar(Context context) {
        try {

            boolean showNavigationBar = false;

            Class systemPropertiesClass = Class.forName("android.os.SystemProperties");
            Method m = systemPropertiesClass.getMethod("get", String.class);
            String navBarOverride = (String) m.invoke(systemPropertiesClass, "qemu.hw.mainkeys");
            if ("1".equals(navBarOverride)) {
                showNavigationBar = false;
            } else if ("0".equals(navBarOverride)) {
                showNavigationBar = true;
            } else if (TextUtils.isEmpty(navBarOverride)) {
                return true;
            }

            return showNavigationBar;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    private static int getWindowManagerLayoutParamsFlag(String fieldString) {
        Class<?> c = null;
        Object obj = null;
        Field field = null;
        try {
            c = Class.forName("android.view.WindowManager$LayoutParams");
            obj = c.newInstance();
            field = c.getField(fieldString);
            int flags = Integer.parseInt(field.get(obj).toString());
            return flags;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return -1;
    }
}
